import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class NetCenter {
  static const String GET = 'GET';
  static const String POST = 'POST';
  static const String PUT = 'PUT';
  static const String DELETE = 'DELETE';
  static const String FILE = 'FILE';

  NetCenter._();

  static final BaseOptions options = BaseOptions(
      baseUrl: 'https://tracking.sshine.ltd/api', //基础Url
      method: 'GET',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 3),
      contentType: Headers.jsonContentType);

  static Dio dio = Dio(options);

  static Future<T> request<T>(String url,
      {String method = GET,
      Map<String, dynamic>? params,
      Map<String, dynamic>? headers,
      FormData? fileData}) async {
    final options = Options(method: method, headers: headers);
    Interceptor inter = InterceptorsWrapper(onRequest: (options, handler) {
      return handler.next(options);
    }, onResponse: (e, handler) {
      if (kDebugMode) {
        print("OnResponse In NC : $e");
      }
      return handler.next(e);
    }, onError: (e, handler) {
      if (kDebugMode) {
        print("OnError In NC : $e");
      }
      return handler.next(e);
    });

    List<Interceptor> inters = [];
    inters.add(inter); //添加自定义拦截器
    inters.add(LogInterceptor()); //添加内置拦截器

    dio.interceptors.addAll(inters);

    try {
      late Response response;
      if (method == GET) {
        response = await dio.request<T>(url,
            queryParameters: params, options: options);
      } else if (method == POST) {
        response = await dio.request<T>(url, data: params, options: options);
      } else if (method == PUT) {
        response = await dio.request<T>(url, data: params, options: options);
      } else if (method == DELETE) {
        response = await dio.request<T>(url,
            queryParameters: params, options: options);
      } else if (method == FILE) {
        response = await dio.request<T>(url,
            data: fileData, options: Options(method: 'POST', headers: headers));
      }
      return response.data;
    } catch (e) {
      return Future.error(e);
    }
  }
}
